package org.chen.utils;

import lombok.extern.slf4j.Slf4j;
import org.chen.domain.entity.Category;
import org.chen.domain.vo.CategoryVO;

import java.util.*;

@Slf4j
public class CategoryTreeUtil {
    
    public static List<CategoryVO> buildTree(List<Category> categories) {
        Map<String, CategoryVO> voMap = new HashMap<>();
        
        // 转换所有分类为VO
        for (Category category : categories) {
            CategoryVO vo = convertToVO(category);
            voMap.put(category.getId(), vo);
        }
        
        // 构建树形结构
        List<CategoryVO> tree = new ArrayList<>();
        for (CategoryVO vo : voMap.values()) {
            if (vo.getParentId() == null) {
                tree.add(vo);
            } else {
                CategoryVO parent = voMap.get(vo.getParentId());
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(vo);
                }
            }
        }
        
        // 排序
        sortTree(tree);
        return tree;
    }

    public static CategoryVO convertToVO(Category category) {
        if (category == null) {
            return null;
        }

        return CategoryVO.builder()
                .id(category.getId())
                .name(category.getName())
                .code(category.getCode())
                .parentId(category.getParentId())
                .level(category.getLevel())
                .path(category.getPath())
                .sort(category.getSort())
                .icon(category.getIcon())
                .description(category.getDescription())
                .type(category.getType())
                .children(new ArrayList<>())
                .build();
    }
    
    private static void sortTree(List<CategoryVO> categories) {
        if (categories == null) return;
        
        categories.sort(Comparator.comparing(CategoryVO::getSort));
        for (CategoryVO category : categories) {
            if (category.getChildren() != null) {
                sortTree(category.getChildren());
            }
        }
    }
}